<template>
    <div class="department-page">
        <!-- 顶部导航栏 -->
        <van-nav-bar title="选择科室" left-arrow @click-left="onBack" :border="false">
            <template #right>
                <van-icon name="ellipsis" size="18" class="nav-icon" />
                <van-icon name="search" size="18" class="nav-icon ml-3" />
            </template>
        </van-nav-bar>

        <!-- 页面内容 -->
        <div class="page-content">
            <!-- 院区选择标签 -->
            <div class="hospital-tabs">
                <van-tabs v-model:active="activeTab" @change="onTabChange" color="#1989fa">
                    <van-tab title="湘南院区" name="xiangnan"></van-tab>
                    <van-tab title="东院" name="east"></van-tab>
                    <van-tab title="北院" name="north"></van-tab>
                </van-tabs>
            </div>

            <!-- 科室选择区域 -->
            <div class="department-container">
                <!-- 左侧主科室列表 -->
                <div class="main-departments">
                    <div v-for="department in mainDepartments" :key="department.value" 
                         class="main-department-item"
                         :class="{ active: selectedMainDepartment?.value === department.value }"
                         @click="selectMainDepartment(department)">
                        {{ department.label }}
                    </div>
                </div>

                <!-- 右侧子科室列表 -->
                <div class="sub-departments">
                    <div v-for="subDept in subDepartments" :key="subDept.value" 
                         class="sub-department-item"
                         @click="selectSubDepartment(subDept)">
                        {{ subDept.label }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const activeTab = ref<'xiangnan' | 'east' | 'north'>('xiangnan')

// 定义科室类型
interface DepartmentItem {
    value: number
    label: string
    children: DepartmentItem[]
}

// 科室数据
const departmentData = ref<DepartmentItem[]>([])
const selectedMainDepartment = ref<DepartmentItem | null>(null)

// 主科室列表
const mainDepartments = computed(() => {
    return departmentData.value || []
})

// 子科室列表
const subDepartments = computed(() => {
    return selectedMainDepartment.value?.children || []
})

// 返回上一页
const onBack = () => {
    router.back()
}

// 切换院区
const onTabChange = (name: string | number) => {
    console.log('切换院区:', name)
    // 重新加载科室数据
    loadDepartments()
}

// 选择主科室
const selectMainDepartment = (department: DepartmentItem) => {
    selectedMainDepartment.value = department
    console.log('选择主科室:', department)
}

// 选择子科室
const selectSubDepartment = (subDept: DepartmentItem) => {
    console.log('选择子科室:', subDept)
    
    // 获取路由参数中的患者信息（如果有的话）
    const patientInfo = {
        patientId: route.query.patientId,
        name: route.query.name,
        relationship: route.query.relationship,
        idCardType: route.query.idCardType,
        idCardNum: route.query.idCardNum,
        medicalCard: route.query.medicalCard,
        phone: route.query.phone,
        address: route.query.address
    }
    
    // 跳转到预约排班页面，传递科室信息
    router.push({
        name: 'appointment-schedule',
        params: {
            departmentId: subDept.value.toString()
        },
        query: {
            // 传递患者信息（如果有的话）
            ...patientInfo,
            // 传递科室信息用于反填
            departmentName: subDept.label,
            mainDepartmentId: selectedMainDepartment.value?.value.toString(),
            mainDepartmentName: selectedMainDepartment.value?.label,
            // 如果有预约ID，也传递过去用于反填
            appointmentId: route.query.appointmentId
        }
    })
}

// 获取科室列表
const loadDepartments = async () => {
    try {
        const response = await axios.get('http://localhost:5103/api/Manage/Handle')
        if (response.data.code === 200) {
            departmentData.value = response.data.data || []
            // 默认选择第一个主科室
            if (departmentData.value.length > 0) {
                selectedMainDepartment.value = departmentData.value[0]
            }
            console.log('科室列表数据：', response.data.data)
        } else {
            console.error('获取科室列表失败:', response.data.message)
        }
    } catch (error) {
        console.error('获取科室列表失败:', error)
        // 使用默认数据
        departmentData.value = [
            {
                value: 1,
                label: '内科',
                children: [
                    { value: 2, label: '神经内科', children: [] },
                    { value: 3, label: '泌尿内科', children: [] },
                    { value: 4, label: '心脏内科', children: [] }
                ]
            },
            {
                value: 5,
                label: '外科',
                children: [
                    { value: 6, label: '普通外科', children: [] },
                    { value: 7, label: '骨科', children: [] }
                ]
            }
        ]
        if (departmentData.value.length > 0) {
            selectedMainDepartment.value = departmentData.value[0]
        }
    }
}

// 页面加载时获取数据
onMounted(() => {
    loadDepartments()
})
</script>

<style scoped>
.department-page {
    min-height: 100vh;
    background-color: #f7f8fa;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.van-nav-bar__title) {
    font-size: 17px;
    font-weight: 600;
    color: #323233;
}

.nav-icon {
    color: #323233;
}

.ml-3 {
    margin-left: 12px;
}

.page-content {
    background-color: #fff;
}

/* 院区选择标签样式 */
.hospital-tabs {
    background-color: #fff;
    padding: 0 16px;
}

:deep(.van-tabs__wrap) {
    border-bottom: 1px solid #f7f8fa;
}

:deep(.van-tab) {
    font-size: 15px;
    font-weight: 500;
    color: #969799;
    padding: 0 20px;
}

:deep(.van-tab--active) {
    color: #1989fa;
    font-weight: 600;
}

:deep(.van-tabs__line) {
    background-color: #1989fa;
    height: 3px;
    border-radius: 2px;
}

/* 科室选择容器 */
.department-container {
    display: flex;
    height: calc(100vh - 140px);
    background-color: #f7f8fa;
}

/* 左侧主科室列表 */
.main-departments {
    width: 120px;
    background-color: #fff;
    border-right: 1px solid #f7f8fa;
}

.main-department-item {
    padding: 20px 16px;
    font-size: 15px;
    color: #323233;
    cursor: pointer;
    transition: all 0.2s;
    border-bottom: 1px solid #f7f8fa;
    text-align: center;
}

.main-department-item:last-child {
    border-bottom: none;
}

.main-department-item:hover {
    background-color: #f7f8fa;
}

.main-department-item.active {
    background-color: #1989fa;
    color: #fff;
    font-weight: 500;
}

/* 右侧子科室列表 */
.sub-departments {
    flex: 1;
    background-color: #f7f8fa;
    padding: 16px;
}

.sub-department-item {
    background-color: #fff;
    margin-bottom: 1px;
    padding: 20px 16px;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 15px;
    color: #323233;
}

.sub-department-item:last-child {
    margin-bottom: 0;
}

.sub-department-item:hover {
    background-color: #f7f8fa;
}

.sub-department-item:active {
    background-color: #e8f4ff;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .main-departments {
        width: 100px;
    }
    
    .main-department-item {
        padding: 16px 12px;
        font-size: 14px;
    }
    
    .sub-department-item {
        padding: 16px;
        font-size: 14px;
    }
}

/* iPhone 样式适配 */
@media (max-width: 414px) {
    .hospital-tabs {
        padding: 0 12px;
    }

    .main-departments {
        width: 90px;
    }
    
    .main-department-item {
        padding: 14px 8px;
        font-size: 13px;
    }
    
    .sub-departments {
        padding: 12px;
    }
    
    .sub-department-item {
        padding: 14px 12px;
        font-size: 13px;
    }

    :deep(.van-tab) {
        padding: 0 16px;
        font-size: 14px;
    }
}
</style>